package com.itttq.gen.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itttq.gen.common.constant.StatusTypeEnums;
import com.itttq.gen.model.po.AccountPo;
import com.itttq.gen.model.qo.AccountQo;
import com.itttq.gen.model.to.IdsTo;
import com.itttq.gen.model.to.ResultTo;
import com.itttq.gen.service.AccountService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;

@RestController
@RequestMapping("account")
@Api(tags = "account")
public class AccountController extends BaseController {
    @Autowired
    private AccountService accountService;
    /**
     * 保存到数据库。如果传入的对象有ID，则更新对象；没有ID则新增对象
     * @param account 保存的对象
     */
    @PostMapping("/save")
    public void saveAccount(@RequestBody @NotNull @Validated AccountPo account) {
        if (null == account.getId()) {
            accountService.addAccount(account);
        } else {
            accountService.updateAccount(account);
        }
    }

    /**
     * 根据ID删除记录
     * @param id
     */
    @PostMapping("/del/{id}")
    public void del(@PathVariable("id") long id) {
        accountService.delAccount(id);
    }
    /**
     * 根据ID获取单个对象信息
     * @param id
     */
    @GetMapping("/account/{id}}")
    public AccountPo account(@PathVariable("id") long id) {
        return accountService.getAccount(id);
    }

    /**
     * 根据条件查询记录并分页
     * @param accountQo 查询对象
     */
    @GetMapping("/accounts")
    public IPage<AccountPo> accounts(AccountQo accountQo) {
        return accountService.getAccountAndPage(accountQo);
    }

    /**
     * 根据条件查询记录不分页
     * @param accountQo 查询对象
     */
    @GetMapping("/accountList")
    public List<AccountPo> accountList(AccountQo accountQo) {
        return accountService.getAccounts(accountQo);
    }

    @GetMapping("/info")
    public AccountPo info() {
        return getAccount();
    }
    /**
     * 根据ID集合批量删除数据
     * @param idsTo ID集合对象
     */
    @PostMapping("/delBatch")
    public void delBatch(@RequestBody IdsTo idsTo) {
        Assert.isTrue(null != idsTo && null != idsTo.getIds(), ResultTo.getCodeAndMsg(ResultTo.ResultCode.DATA_NO, "请选择要删除的记录"));
        accountService.delAccountByIds(idsTo.getIds());
    }

    @PostMapping("/disable/{id}")
    public void disable(@PathVariable("id") long id) {
        updateStatus(id, StatusTypeEnums.StatusEnums.DISABLE);
    }

    @PostMapping("/enable/{id}")
    public void enable(@PathVariable("id") long id) {
        updateStatus(id, StatusTypeEnums.StatusEnums.ENABLE);
    }

    public void updateStatus(Long userId, StatusTypeEnums.StatusEnums status) {
        accountService.updateAccount(AccountPo.builder().id(userId).status(status).build());
    }
}
